package com.intelligencesoft.pss.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.intelligencesoft.pss.auth.LoginUtil;
import com.intelligencesoft.pss.entity.base.PageBean;
import com.intelligencesoft.pss.entity.base.UserInfo;
import com.intelligencesoft.pss.entity.binding.BindingList;
import com.intelligencesoft.pss.entity.binding.UserBinding;
import com.intelligencesoft.pss.entity.publish.PublishImage;
import com.intelligencesoft.pss.entity.publish.PublishInfo;
import com.intelligencesoft.pss.enums.BindingType;
import com.intelligencesoft.pss.service.PublishInfoService;
import com.intelligencesoft.pss.service.SysMenuService;
import com.intelligencesoft.pss.service.binding.BindingListService;
import com.intelligencesoft.pss.service.binding.UserBindingService;
import com.intelligencesoft.pss.sina.weibo.weibo4j.Oauth;
import com.intelligencesoft.pss.sina.weibo.weibo4j.Timeline;
import com.intelligencesoft.pss.sina.weibo.weibo4j.Users;
import com.intelligencesoft.pss.sina.weibo.weibo4j.http.ImageItem;
import com.intelligencesoft.pss.sina.weibo.weibo4j.model.Status;
import com.intelligencesoft.pss.sina.weibo.weibo4j.model.WeiboException;
import com.intelligencesoft.pss.tencent.weibo.api.TAPI;
import com.intelligencesoft.pss.tencent.weibo.oauthv2.OAuthV2;
import com.intelligencesoft.pss.tencent.weibo.oauthv2.OAuthV2Client;

@Controller
@RequestMapping(value="/publishInfo")
public class PublishInfoController {

	@Autowired
	private LoginUtil loginUtil;
	
	@Autowired
	@Qualifier("configProperties")
	private Properties properties;
	
	@Autowired
	private BindingListService bindingListService;
	
	@Autowired
	private SysMenuService sysMenuService;
	
	@Autowired
	private UserBindingService userBindingService;
	
	@Autowired
	private Oauth oauth;
	
	@Autowired
	private Users users;
	
	@Autowired
	private Timeline timeline;
	
	@Autowired
	private HttpServletRequest request;
	
	@Autowired
	private PublishInfoService publishInfoService;
	
	
	@RequestMapping(value="/getUserPublishInfo",method=RequestMethod.GET)
	@ResponseBody
	public ModelMap getUserPublishInfo(PublishInfo publishInfo,PageBean pageBean){
		UserInfo userInfo = loginUtil.getLoginUser();
		List<PublishInfo> publishInfos = null;
		int total = 0;
		if(userInfo != null){
			publishInfo.setUserInfo(userInfo);
			total = publishInfoService.publishCount(publishInfo);
			publishInfos = publishInfoService.findPublishInfoPageData(publishInfo, pageBean);
		}
		int pageSize = pageBean.getPageSize();
		int pageNumber = pageBean.getPageNumber();
		ModelMap modelMap = new ModelMap();
		modelMap.put("total", total);
		modelMap.put("pageSize", pageSize);
		modelMap.put("pageNumber", pageNumber);
		modelMap.put("publishInfos", publishInfos);
		return modelMap;
	}
	
	@RequestMapping(value="/publishInfo",method=RequestMethod.POST)
	@ResponseBody
	public ModelAndView publishInfo(PublishInfo info,String imagePath) throws Exception{
		ModelAndView modelAndView = new ModelAndView();
		
		UserInfo userInfo = loginUtil.getLoginUser();
		
		List<UserBinding> userBindings = userBindingService.findUserBindsByUserId(userInfo.getId());
		
		for (UserBinding userBinding : userBindings) {
			BindingList bindingList = userBinding.getBindingList();
			if(!bindingList.getId().equals(info.getBindingType())){
				continue;
			}
			BindingType type = userBinding.getBindingList().getBindingType();
			switch (type) {
			case BINDING_SINA_WEIBO:
				publishSinaInfo(info,imagePath,BindingType.BINDING_SINA_WEIBO);
				info.setUserInfo(userInfo);
				savePublishInfo(info);
				break;
			case BINDING_TENCENT_WEIBO:
				publishTencentInfo(info, imagePath, BindingType.BINDING_TENCENT_WEIBO);
				break;
			case BINDING_MICROMSG:
				
				break;
			default:
				savePublishInfo(info);
				break;
			}
		}
		return modelAndView;
	}
	
	@RequestMapping(value="/upImage",method=RequestMethod.POST)
	@ResponseBody
	public ModelMap upImage(MultipartHttpServletRequest request){
		MultipartFile multiFile = request.getFile("picImage");
		String savePath = request.getServletContext().getRealPath("/");
		String nowDate = new SimpleDateFormat("yyyyMMddhhmmssSSS").format(new Date());
		savePath +=  "upload" ;
		File file = new File(savePath);
		file.mkdirs();
		savePath += File.separatorChar + nowDate + ".jpg";
		File imageFile = new File(savePath);
		String fileName = imageFile.getName();
		try {
			multiFile.transferTo(imageFile);
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ModelMap  modelMap = new ModelMap();
		modelMap.put("path", request.getServletContext().getContextPath() + "/upload/" + fileName);
		return modelMap;
	}
	
	private void savePublishInfo (PublishInfo publishInfo){
		publishInfoService.save(publishInfo);
	}
	
	private void savePublishPic(String imageFile){
		
	}
	private void publishTencentInfo(PublishInfo info,String imageFile,BindingType type) throws Exception{
		UserInfo userInfo = loginUtil.getLoginUser();
		String userId = userInfo.getId();
		String clientId = properties.getProperty("tencent_app_id");
		String clientSecret = properties.getProperty("tencent_app_key");
		String redirectUri = properties.getProperty("tencent_redirect_URI");
		OAuthV2 oAuthV2 = new OAuthV2(clientId, clientSecret, redirectUri);
		String access_Token = oAuthV2.getAccessToken();
		if(StringUtils.isNotBlank(userId)){
			UserBinding userBinding = userBindingService.findUserBindsByUserIdAndType(userId,type);
			if(userBinding != null){
				oAuthV2.setOpenid(userBinding.getOpenId());
				oAuthV2.setOpenkey(userBinding.getOpenKey());
				oAuthV2.setAccessToken(userBinding.getAccessToken());
			}
		}
		OAuthV2Client oAuthV2Client = new OAuthV2Client();
		boolean isToken = oAuthV2Client.accessToken(oAuthV2);
		
		String oAuthVersion = oAuthV2.getOauthVersion();
		
		TAPI tAPI=new TAPI(oAuthVersion);//根据oAuth配置对应的连接管理器
		 //取得返回结果
		String response = "";
		if(StringUtils.isNotBlank(imageFile)){
			response = tAPI.addPic(oAuthV2, "json", info.getText(), getIPAddress(), "", "",imageFile, "1");
			response = tAPI.addPic(oAuthV2, "json", info.getText(), getIPAddress(), "", "",imageFile, "1");
		}else{
			response = tAPI.add(oAuthV2, "json", info.getText(), getIPAddress(), "", "", "1");
		}
             // json数据使用
             // response的结果可能是这样，{"data":{"id":"90221131024999","time":1333002978},"errcode":0,"msg":"ok","ret":0}
             // 下面的代码将取出 id 的对应值，并赋予 reid
            System.out.println("response = "+response);
            JSONObject responseJsonObject;
            JSONObject dataJsonObject;
            responseJsonObject= JSONObject.fromObject(response);
            dataJsonObject=(JSONObject)responseJsonObject.get("data");
            String uid = dataJsonObject.get("id").toString();//对后面用到的 reid 赋值
        try { Thread.sleep ( 5000 ) ; } catch (InterruptedException ie){}
        
        
        tAPI.shutdownConnection();//关闭连接管理器
	}
	/**
	 * 新浪微博发布
	 * @author 黄莹璐
	 * @date: 2014-9-21-下午10:43:51
	 * //TODO  黄莹璐编辑
	 * @param info
	 * @param imageFile
	 */
	private void publishSinaInfo(PublishInfo info,String imageFile,BindingType type){
		String userId = loginUtil.getLoginUser().getId();
		if(StringUtils.isNotBlank(userId)){
			UserBinding userBinding = userBindingService.findUserBindsByUserIdAndType(userId,type);
			String accessToken = userBinding.getAccessToken();
			timeline.setAccess_token(accessToken);
			try {
				Status updateStatus = null;
				if(StringUtils.isNotBlank(imageFile)){
					imageFile = imageFile.substring(imageFile.lastIndexOf("/") + 1,imageFile.length());
					String savePath = request.getServletContext().getRealPath("/");
					savePath +=  "upload" ;
					savePath += File.separatorChar + imageFile;
					byte[] content = readFileImage(savePath);
					System.out.println("content length:" + content.length);
					ImageItem pic = new ImageItem("pic", content);
					String s = java.net.URLEncoder.encode(info.getText(), "utf-8");
					PublishImage publishImage = new PublishImage();
					publishImage.setImagePath(savePath);
					List<PublishImage> publishImages = new ArrayList<PublishImage>();
					info.setPublishImage(publishImages);
//					updateStatus = timeline.uploadStatus(s, pic);
				}else{
					updateStatus = timeline.updateStatus(info.getText());
				}
			} catch (WeiboException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	private byte[] readFileImage(String filename) throws IOException {
		BufferedInputStream bufferedInputStream = new BufferedInputStream(
				new FileInputStream(filename));
		int len = bufferedInputStream.available();
		byte[] bytes = new byte[len];
		int r = bufferedInputStream.read(bytes);
		if (len != r) {
			bytes = null;
			throw new IOException("读取文件不正确");
		}
		bufferedInputStream.close();
		return bytes;
	}
	
	
	private String getIPAddress(){
		String ip = "";
		ip = request.getRemoteAddr();
		return ip;
	}
	
}
